package com.bcx.wind.workflow.db.util;

import com.bcx.wind.workflow.db.util.handler.ResultSetHandler;
import com.sun.org.apache.bcel.internal.generic.RETURN;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 工作流db 持久层工具
 *
 * @author zhanglei
 */
public class WindDbRunner implements DbRunner{


    @Override
    @SuppressWarnings("unchecked")
    public <T> T query(Connection connection, String sql, ResultSetHandler handler, Object[] args)throws SQLException {
        PreparedStatement statement = connection.prepareStatement(sql);
        injectArgs(statement,args);
        ResultSet resultSet =  statement.executeQuery();
        //执行拦截
        return (T) handler.handle(resultSet);
    }


    @Override
    public int saveOrUpdate(Connection connection, String sql, Object[] args) throws SQLException{
        PreparedStatement statement = connection.prepareStatement(sql);
        injectArgs(statement,args);
        return statement.executeUpdate();
    }



    @Override
    public int saveOrUpdate(Connection connection, String sql) throws SQLException {
        PreparedStatement statement = connection.prepareStatement(sql);
        return statement.executeUpdate();
    }


    /**
     * 在statement中注入参数
     *
     * @param statement   statement
     * @param args        参数
     */
    private void  injectArgs(PreparedStatement statement,Object[] args) throws SQLException {
        if(args == null){
            return ;
        }

        for(int i=0 ; i<args.length ; i++){
            Object obj = args[i];
            statement.setObject(i+1,obj);
        }
    }

}
